package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.MobileExistException;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import com.atguigu.gulimall.member.vo.MemberRegistVo;
import com.atguigu.gulimall.member.vo.SocialUserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;


import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;
import org.springframework.transaction.annotation.Transactional;


@Service("memberService")
@Slf4j
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void regist(MemberRegistVo registVo) {
        MemberEntity memberEntity = new MemberEntity();

        //设置默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());
        memberEntity.setUsername(registVo.getUserName());

        checkMobilePhoneUnique(registVo.getMobilePhone());
        checkUserNameUnique(memberEntity.getUsername());
        //密码要进行加密后再保存
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(registVo.getPassword());
        memberEntity.setPassword(encode);
        memberEntity.setMobile(registVo.getMobilePhone());


        baseMapper.insert(memberEntity);

    }

    @Override
    public void checkMobilePhoneUnique(String mobilePhone) {

        Integer selectCount = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("phone", mobilePhone));
        if (selectCount > 0) {
            throw new MobileExistException();
        }
    }

    @Override
    public void checkUserNameUnique(String userName) {
        Integer selectCount = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("user_name", userName));
        if (selectCount > 0) {
            throw new MobileExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo loginVo) {

        String loginacct = loginVo.getLoginacct();
        String password = loginVo.getPassword();

        MemberEntity entity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));

        if (entity == null) {
            return null;
        } else {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            boolean matches = encoder.matches(password, entity.getPassword());
            if (matches) {
                return entity;
            } else {
                return null;
            }
        }
    }

    /**
     * 社交账号的登录
     **/
    @Override
    @Transactional
    public MemberEntity oauthLogin(SocialUserVo loginVo) throws Exception {

        String uid = loginVo.getUid();
        MemberEntity entity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uuid", uid));
        if (entity != null) {
            MemberEntity memberEntity = new MemberEntity();
            memberEntity.setId(entity.getId());
            memberEntity.setAccessToken(loginVo.getAccess_token());
            memberEntity.setExpiresIn(loginVo.getExpires_in());
            baseMapper.updateById(memberEntity);
            entity.setAccessToken(loginVo.getAccess_token());
            entity.setExpiresIn(loginVo.getExpires_in());
            return entity;
        } else {
            MemberEntity memberEntity = new MemberEntity();
            try {
                //查询当前社交用户允许获得的信息,并保存到数据库
                Map<String, String> query = new HashMap();
                query.put("access_token",loginVo.getAccess_token());
                query.put("uid",loginVo.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo", "/2/users/show.json", "get", null, query);

                if (response.getStatusLine().getStatusCode() == 200){
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSONObject.parseObject(json);
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    //还有其他文档开放的所有信息,就自行获取;
                    memberEntity.setNickname(name);
                    memberEntity.setGender("男".equals(gender) ? 1 : 0);
                }
            } catch (Exception e) {
                log.info("远程查询用户信息报错======");
            }

            memberEntity.setId(entity.getId());
            memberEntity.setAccessToken(loginVo.getAccess_token());
            memberEntity.setExpiresIn(loginVo.getExpires_in());
            //TODO 还有一些其他的默认字段,在自行设置
            baseMapper.insert(memberEntity);
            return memberEntity;
        }
    }

}